
package com.kugou.game.sdk.utils;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;

import com.kugou.framework.service.ISSOService;

public class BindSSOServiceHelper {

    public static interface OnSSOServiceBindListener {

        /**
         * 绑定成功
         * 
         * @param context
         * @param service
         */
        void onSSOServiceBinded(Context context, ISSOService service);

        void onSSOServiceBindFailed();
    }

    /**
     * 绑定 SSO service
     * 
     * @param context
     * @param listener
     */
    public synchronized static ServiceConnection bindSSOService(Context context,
            OnSSOServiceBindListener listener) {
        ServiceConnection conn;
        Intent service = new Intent();
        service.setPackage("com.kugou.android");
        service.setClassName("com.kugou.android", "com.kugou.framework.service.SSOService");
        conn = new ServiceConnectionForSSO(context, listener);
        boolean isSuccess = context.bindService(service, conn, Context.BIND_AUTO_CREATE);
        if (!isSuccess) {
            listener.onSSOServiceBindFailed();
        }
        return conn;
    }

    static class ServiceConnectionForSSO implements ServiceConnection {

        private Context mContext;

        private OnSSOServiceBindListener mListener;

        public ServiceConnectionForSSO(Context context, OnSSOServiceBindListener listener) {
            mContext = context;
            mListener = listener;
        }

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            final ISSOService remoteService = ISSOService.Stub.asInterface(service);
            mListener.onSSOServiceBinded(mContext, remoteService);
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
        }

    }

}
